package com.laicunba.service.impl;

import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.laicunba.service.MessagePushService;
import com.laicunba.util.StringUtil;

@Service
public class MessagePushServiceJPushImpl implements MessagePushService {
	private static final Logger LOG = Logger.getLogger(MessagePushServiceJPushImpl.class);
	@Value("${jpush.appkey}")
	private String appKey;
	@Value("${jpush.secret}")
	private String secret;
	@Value("${jpush.url}")
	private String url;
	@Value("${jpush.product}")
	private String product;

	private static String BASIC_AUTH;
	private static String AUTH_KEY = "Authorization";

	@SuppressWarnings("unchecked")
	@Override
	public boolean post(String pushId, Message msg) {
		if (StringUtil.isEmpty(BASIC_AUTH)) {

			BASIC_AUTH = "Basic " + Base64.encodeBase64String((appKey + ":" + secret).getBytes());
		}

		HttpsURLConnection conn = null;
		try {
			URL reqUrl = new URL(url);
			conn = (HttpsURLConnection) reqUrl.openConnection();
			conn.setRequestProperty(AUTH_KEY, BASIC_AUTH);

			conn.setDoOutput(true);
			conn.addRequestProperty("Content-Type", "application/json");

			JSONObject json = new JSONObject();
			json.put("title", msg.getTitle());
			json.put("app_view", msg.getAppView());
			json.put("subTitle", msg.getSubTitle());
			json.put("href", msg.getHref());

			StringBuilder sb = new StringBuilder();
			sb.append("{\"platform\":\"all\",\"audience\":{\"registration_id\":[\"");
			sb.append(pushId).append("\"]},\"notification\":{\"alert\":\"");
			sb.append(msg.getSubTitle()).append("\",\"android\":{\"extras\":" + json.toJSONString() + "}");
			sb.append(",\"ios\":{\"extras\":" + json.toJSONString() + "}").append("}");
			sb.append(",\"options\":{\"apns_production\": " + "true".equalsIgnoreCase(product) + "}}");
			System.out.println(sb.toString());
			conn.getOutputStream().write(sb.toString().getBytes("utf-8"));
			if (conn.getResponseCode() == 200) {
				String response = IOUtils.toString(conn.getInputStream(), "utf-8");
				LOG.info(response);
				return true;
			} else {
				LOG.warn("send jpush not success:" + sb.toString());
				LOG.warn(IOUtils.toString(conn.getInputStream(), "utf-8"));
				return false;
			}
		} catch (Exception e) {
			LOG.error("send jpush error", e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean post(Message msg) {
		if (StringUtil.isEmpty(BASIC_AUTH)) {

			BASIC_AUTH = "Basic " + Base64.encodeBase64String((appKey + ":" + secret).getBytes());
		}

		HttpsURLConnection conn = null;
		try {
			URL reqUrl = new URL(url);
			conn = (HttpsURLConnection) reqUrl.openConnection();
			conn.setRequestProperty(AUTH_KEY, BASIC_AUTH);

			conn.setDoOutput(true);
			conn.addRequestProperty("Content-Type", "application/json");

			JSONObject json = new JSONObject();
			json.put("title", msg.getTitle());
			json.put("app_view", msg.getAppView());
			json.put("subTitle", msg.getSubTitle());
			json.put("href", msg.getHref());

			StringBuilder sb = new StringBuilder();
			sb.append("{\"platform\":\"all\",\"audience\":\"all\",\"notification\":{\"alert\":\"");
			sb.append(msg.getSubTitle()).append("\",\"android\":{\"extras\":" + json.toJSONString() + "}");
			sb.append(",\"ios\":{\"extras\":" + json.toJSONString() + "}").append("}");
			sb.append(",\"options\":{\"apns_production\": " + "true".equalsIgnoreCase(product) + "}}");
			System.out.println(sb.toString());
			conn.getOutputStream().write(sb.toString().getBytes("utf-8"));
			if (conn.getResponseCode() == 200) {
				String response = IOUtils.toString(conn.getInputStream(), "utf-8");
				LOG.info(response);
				return true;
			} else {
				LOG.warn("send jpush not success:" + sb.toString());
				LOG.warn(IOUtils.toString(conn.getInputStream(), "utf-8"));
				return false;
			}
		} catch (Exception e) {
			LOG.error("send jpush error", e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return false;
	}

}
